package com.yuqingxin.redisCacheApi.util;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author yuqingxin
 * */
@Service
public class ArgumentsUtil {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 参数类型转换为对应对象
     * */
    public Class<?>[] getClassArray(String typesString){
        String[] classNames = typesString.substring(1, typesString.length() - 1).split("class ");
        Class<?>[] classes = new Class<?>[classNames.length-1];

        for (int i = 1; i < classNames.length; i++) {
            try {
                Class<?> clazz = Class.forName(classNames[i].replace(", ",""));
                classes[i-1] = clazz;
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return classes;
    }

    /**
     * 参数值转换为对象
     * */
    public Object[] getObjectArray(String argumentsString,Class<?>[] parameterTypes) {
        Object[] objects = JSON.parseObject(argumentsString,Object[].class);
        for (int i = 0; i < objects.length; i++) {
            try {
                objects[i] = objectMapper.readValue(objectMapper.writeValueAsString(objects[i]),parameterTypes[i]);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return objects;
    }
}
